#coding=utf-8

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
import os
from google.appengine.ext.webapp import template
import logging

class Baby(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  name = db.StringProperty(multiline=True);

class Babybook(webapp.RequestHandler):
  def post(self):
    baby = Baby();

    if users.get_current_user():
        logging.debug("get current user");
        baby.author = users.get_current_user()
    
    logging.info("hh");
    
    baby.content = self.request.get('content')
    baby.name=self.request.get('content');
    baby.put()
    self.redirect('/')  
  
class MainPage(webapp.RequestHandler):
    def get(self):
        logging.debug("hello,China!");
        
        babys_query = Baby.all().order('-date')
        babys = babys_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'babys': babys,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__),'templates','index.html')
        self.response.out.write(template.render(path, template_values))

def main():
    logging.getLogger().setLevel(logging.INFO)

    application = webapp.WSGIApplication(
                                       [
                                        ('/', MainPage),
                                        ('/sign',Babybook)
                                        ],
                                       debug=True)
                                    
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
